import React, {Component} from 'react';
import './comment.css';

export default class Comment extends Component {

    constructor() {
        super();
        this.state = {
            timeString: ""
        }
    }

    componentWillMount() {
        this._updateTiming();
        this._timer = setInterval(this._updateTiming.bind(this), 4000);

    }

    componentWillUnmount(){
        clearInterval(this._timer)
    }

    _updateTiming() {
        const comment = this.props.comment;
        const duration = (+ Date.now() - comment.dateTime) / 1000
        this.setState({
            timeString: duration > 60
                ? `${Math.round(duration / 60)} 分钟前`
                : `${Math.round(Math.max(duration, 1))} 秒前`
        })
    }

    handleCommentDelete(){
        if(this.props.onDeleteComment){
            this.props.onDeleteComment(this.props.index);
        }
    }

    render() {
        return (
            <div className="comment-list">

                <div className="comment-each">
                    <h3>{this.props.comment.username}</h3>
                    <p>{this.props.comment.content}</p>
                    <span className="time">{this.state.timeString}</span>

                    <button className="comment-delete" onClick={this.handleCommentDelete.bind(this)}>删除</button>

                </div>

            </div>
        )
    }
}
